﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using SARS.Biz;
using SARS.Entity;

namespace SARS.Course.Group
{
    public partial class AssignGroupTutor : Page
    {
        private readonly GroupBO groupBiz = new GroupBO();
        private readonly UserBO userBiz = new UserBO();
        private GroupEntity group;
        private int? groupId;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetNoStore();
            if (!string.IsNullOrEmpty(Request.QueryString["gid"]))
            {
                groupId = Int32.Parse(Request.QueryString["gid"]);
                if (!IsPostBack)
                {
                    group = groupBiz.RetrieveGroupById(groupId.Value);
                    group.GroupMembers = userBiz.RetrieveStudentByGroupId(groupId.Value);
                    group.GroupTutorial = userBiz.RetrieveTutorsByGroupId(groupId.Value);

                    hdlabel.Text = group.GroupName;
                    lblGroupName.Text = group.GroupName;
                    lbGroupCourse.Text = group.Course.CourseInfo;

                    gvCurrentTutors.DataSource = group.GroupTutorial;
                    gvCurrentTutors.DataBind();

                    List<TutorEntity> list = userBiz.GetAllTutorOutOfGroup(groupId.Value);
                    gvAssignTutor.DataSource = list;
                    gvAssignTutor.DataBind();

                    if (list.Count == 0)
                    {
                        btnSave.Visible = false;
                    }
                }
            }
            else
            {
                Response.Redirect("Group.aspx");
            }
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            Response.Redirect("GroupEdit.aspx?gid=" + groupId);
        }

        protected void btnSave_OnClick(object sender, EventArgs e)
        {
            List<string> assignTutor = GetCheckedTutos();

            foreach (string tutor in assignTutor)
            {
                groupBiz.AssignGroupTutor(groupId.Value, Int32.Parse(tutor));
            }

            Response.Redirect("GroupDetails.aspx?gid=" + groupId.Value);
        }

        private List<string> GetCheckedTutos()
        {
            var checkedIds = new List<string>();

            foreach (GridViewRow gvrow in gvAssignTutor.Rows)
            {
                string index = gvAssignTutor.DataKeys[gvrow.RowIndex].Value.ToString();
                bool result = ((CheckBox) gvrow.FindControl("cbAdd")).Checked;

                if (result)
                {
                    checkedIds.Add(index);
                }
            }
            return checkedIds;
        }
    }
}